package com.itheima.leyou.controller;

import com.itheima.leyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Map;


@RestController
public class UserController {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;

    @Resource
    private UserService userService;

    @RequestMapping(value = "/getUser/{phone}/{password}")
    public ArrayList<Map<String, Object>> getUser(@PathVariable("phone") String phone, @PathVariable("password") String password){
        return userService.getUser(phone, password);
    }

    @RequestMapping(value = "/insertUser/{jsonObj}")
    public Map<String, Object> insertUser(@PathVariable("jsonObj") String jsonObj){
        return userService.insertUser(jsonObj);
    }


    /**
     * linbin
     * 用户登录操作
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Map<String, Object> login(String userName, String password, HttpServletRequest request){

        ArrayList<Map<String, Object>> list = userService.getUser(userName, password);

        Map userMap = null;
        //如果不存在用户直接注册一个
        if(list == null || list.isEmpty()){
            StringBuffer userStrBuf = new StringBuffer("{");
            userStrBuf.append("username:");
            userStrBuf.append(userName);
            userStrBuf.append(",");
            userStrBuf.append("password:");
            userStrBuf.append(password);
            userStrBuf.append(",");
            userStrBuf.append("phone:");
            userStrBuf.append(userName);
            userStrBuf.append("}");
            userMap = userService.insertUser(userStrBuf.toString());
        }
        HttpSession session = request.getSession();
        session.setAttribute("user",list.get(0));
        System.out.println(request.getSession().getId());
        return userMap;
    }
}
